package com.kb5173.search.words.job;

import com.kb5173.search.common.utils.JobLockRedisImpl;
import com.kb5173.search.words.service.IFileService;
import com.kb5173.search.words.service.IWordsService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
* @author Chengfei.Sun
*/
@Component
@Lazy(false)
public class AutoWordsWriteJob {
    protected static final Log log = LogFactory.getLog(AutoWordsWriteJob.class);

    private static final String JOB_ID = "WORDS_WRITE_JOB";

    @Autowired
    IWordsService wordsService;

    @Autowired
    IFileService fileService;

    @Autowired
    JobLockRedisImpl jobLock;

    /**
     * 描述：定时向ikAnalyzer配置分词文件，写入自定义的分词；
     * 间隔时间：1小时
     */
    @Scheduled(cron="* * 0/1 * * ?")
    public void wordsWrite() {
        log.info("分词写入文件定时器开始");
        Boolean locked = jobLock.lock(JOB_ID);
        if(!locked){
            log.info("上一个分词写入还未执行完成。");
            return;
        }

        try {
            List<String> words = wordsService.getWords();
            if (words == null || words.size() == 0) {
                return;
            }
            fileService.wordsWrite(words);
        } finally {
            jobLock.unlock(JOB_ID);
        }
        log.debug("分词写入文件定时器结束");
    }
}
